package client;
import gui.Cart_Gui;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.BorderFactory;
import javax.swing.DefaultCellEditor;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;

public class Catalog extends JFrame implements ActionListener
{ 
	public JTable table;
	public JScrollPane ScrollPane = null;
	public JButton Back = null;
	public JButton logOut = null;
	public JButton goToCart = null;
    public String[] columnNames = {"Name", "Image", "Enlarge", "Price", "Type", "Id", "Cart-Add/Rem", "Costum"};
    public Object[][] data = null;
    public static Object[] specialSale = null;
    public JButton imgbutton = new JButton();
    public JButton cartbutton = new JButton();
    public JButton Custom = new JButton();
    public JFrame imgFrame = new JFrame("Item Image");
    public JPanel imgPanel = new JPanel();
    public JLabel lbl = new JLabel();
    public int counter = -1;
    public static setImage img = null;
    public String callFrom = null;
    public SpinBox sb = null;
    int width = (int)Main.dim.getWidth();
	int height = (int)Main.dim.getHeight();
	
    public Catalog(String From) 
	{
    	callFrom = From;
    	data = Search_Control.tempData;
    	specialSale = Search_Control.onSpecialSale;
        
    	img = new setImage("catalog"); 
        img.setLayout(null);
		
        this.setTitle("Catalog");
		this.setPreferredSize(new Dimension(width-100, height-200));
		this.setLocation((int)Main.dim.getWidth()/2 - (int)this.getPreferredSize().getWidth()/2,(int)Main.dim.getHeight()/2 - (int)this.getPreferredSize().getHeight()/2);
		this.setResizable(false);
	    this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        
        Back = new JButton("Back");
		Back.setBounds((int)this.getPreferredSize().getWidth()-115,10,100,40);
		Back.addActionListener(this);
		img.add(Back);
		
		logOut = new JButton("LogOut");
		logOut.setBounds(10,10,100,40);
		logOut.addActionListener(this);
		img.add(logOut);
		
		goToCart = new JButton("go To Cart");
		goToCart.setBounds((int)this.getPreferredSize().getWidth()-285,10,150,40);
		goToCart.addActionListener(this);
		img.add(goToCart);
        
        table = new JTable(new MyTableModel(data, columnNames, "catalog"));
        table.setPreferredScrollableViewportSize(new Dimension(500, 300));
        table.setFillsViewportHeight(true);
        table.setRowHeight(120);
        
        table.getColumnModel().getColumn(5).setPreferredWidth(1);
        table.setIntercellSpacing(new Dimension(30,30));
        table.setFont(new Font (Font.SANS_SERIF ,Font.ITALIC,18));
		table.getTableHeader().setFont(new Font (Font.SANS_SERIF ,Font.ITALIC,20));
		table.getTableHeader().setForeground(new Color(92,64,51));
        table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        
        final DefaultTableCellRenderer dtcr = new DefaultTableCellRenderer();  
        dtcr.setHorizontalTextPosition(JLabel.CENTER);  
        table.getColumnModel().getColumn(5).setCellRenderer(dtcr);
        table.getColumnModel().getColumn(3).setCellRenderer(dtcr);
        table.setBackground(new Color(253,245,230));
    
        table.getColumnModel().getColumn(2).setCellRenderer(new ButtonRenderer());
        table.getColumnModel().getColumn(2).setCellEditor(new ButtonEditor(new JCheckBox()));
        table.getColumnModel().getColumn(6).setCellRenderer(new ButtonRenderer());
        table.getColumnModel().getColumn(6).setCellEditor(new ButtonEditor(new JCheckBox()));
        table.getColumnModel().getColumn(7).setCellRenderer(new ButtonRenderer());
        table.getColumnModel().getColumn(7).setCellEditor(new ButtonEditor(new JCheckBox()));
        
        table.getColumnModel().getColumn(3).setCellRenderer(new MyTableCellRender());
        
        imgbutton.addActionListener(this);
        cartbutton.addActionListener(this);
        Custom.addActionListener(this);
        
        if(LogIn.usr.getPriv() != 5)
        {
			table.getColumnModel().removeColumn(table.getColumnModel().getColumn(7));
			table.getColumnModel().removeColumn(table.getColumnModel().getColumn(6));
			goToCart.setVisible(false);
        }
        
		ScrollPane = new JScrollPane(table);
		ScrollPane.setBounds(10, 70, (int)this.getPreferredSize().getWidth()-25, (int)this.getPreferredSize().getHeight()-120);
		img.add(ScrollPane);
		this.add(img);
		this.pack();
		this.setVisible(true);
    }
    
    public void actionPerformed(ActionEvent e) 
	{
    	if(e.getSource() == goToCart)
		{
    		if(Main.cart != null)
    			Main.cart.dispose();
    		Main.cart = new Cart_Gui("Catalog");
    		this.setVisible(false);
		}
    	
    	if(e.getSource() == Custom)
		{	
	    	String type = (String)Main.catalog.table.getValueAt(Main.catalog.table.getSelectedRow(), 4);
    		if(type.equals("perah"))	//custom item can only be build from perah 
	    	{
    			if(Main.customOrder != null)
	    			Main.customOrder.dispose();
	    		callFrom = "Costum";
	    		Main.customOrder = new CustomOrder();	
	    		this.setEnabled(false);
	    	}
	    	else JOptionPane.showMessageDialog(null,"This item can not be added to a custom item","Error",JOptionPane.ERROR_MESSAGE);
	    }
    	
    	if(e.getSource() == cartbutton)
		{	
    		Object[] temp = null;
            if(Main.cart_Control != null)
            	Main.cart_Control = null;
            Main.cart_Control = new Cart("getData", temp);
            Main.cart_Control = (Cart)Main.clie.getResult();
            
    		callFrom = "Cart";
			int spinBoxVal = 0;
			for(int i = 0 ; i < Main.cart_Control.dataFromDB.length ; i++)
			{	
				//itemId = the item id in the selected row
				int itemId = (Integer) Main.catalog.table.getValueAt(Main.catalog.table.getSelectedRow(), 5);
				//set in the spinbox the last value that the user entered 
				if((Integer)Main.cart_Control.dataFromDB[i][0] == itemId)
				{
					spinBoxVal = (Integer) Main.cart_Control.dataFromDB[i][4];
					break;
				}
				else
					spinBoxVal = 0;
			}
			sb = new SpinBox(spinBoxVal,0,Integer.MAX_VALUE);
			sb.setBounds(getMousePosition().x-50, getMousePosition().y-10, 205, 175);		
			this.setEnabled(false);
		}
    	
		if(e.getSource() == Back)
		{
			if(Main.main.callFrom.equals("order_GUI"))
			{
				Main.main.order.setEnabled(true);
				Main.main.order.setVisible(true);
			}
			else
			{
				Main.main.setEnabled(true);
				Main.main.setVisible(true);
			}
			this.setVisible(false);
		}
		
		if(e.getSource() == logOut)
		{
			if(JOptionPane.showConfirmDialog(null,"Are you sure you want to logout?",null,JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION)
			{
				this.setVisible(false);
				if(callFrom == "Search")
					MainScreen.src.setVisible(false);
				if(Main.main.callFrom == "order_GUI")
					Main.main.order.setVisible(false);
				
				Main.main.logOut.doClick();
			}
		}
		
		if(e.getSource() == imgbutton)
		{
			int imgNum = (Integer)table.getSelectedRow();
        	if(counter != imgNum)	 
	        {
        		counter = imgNum;
	        	ImageIcon icon = (ImageIcon) Search_Control.imgCounter[imgNum];
        		lbl.setIcon(icon);							

        		imgFrame.setSize(new Dimension(lbl.getWidth()+80, lbl.getHeight()+80));
        		imgFrame.setLocation((int)Main.dim.getWidth()/2 - (int)this.getPreferredSize().getWidth()/2 + 200,(int)Main.dim.getHeight()/2 - (int)this.getPreferredSize().getHeight()/2);
        		imgFrame.setResizable(false);
        		imgPanel.add(lbl);
        
        		imgFrame.addWindowListener(new WindowAdapter() 
                {public void windowClosing(WindowEvent e){imgFrame.dispose();}});
        		
        		imgFrame.add(imgPanel);
        		imgFrame.pack();
        		imgFrame.setVisible(true);
        	}
        	else
        	{
        		counter = -1;
        		imgFrame.setVisible(false);
        	}
		}
	}
    
    class MyTableCellRender extends DefaultTableCellRenderer   
    {  
        public MyTableCellRender()   
        {  
            super();  
            setOpaque(true);  
        }   
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)   
        {   
        	if((Integer)specialSale[row] == 0)  
	        {  
	            setForeground(new Color(92,64,51));        
	            setBackground(new Color(253,245,230));
	            setValue(value);
	            setFont(new Font (Font.SANS_SERIF ,Font.ITALIC,18));
	            return this;  
	        }      
	        else
	        {
	            JTextArea j = new JTextArea();
	            j.setForeground(Color.BLACK);          
	            j.setBackground(new Color(238,18,137));  
	            j.setFont(new Font (Font.SANS_SERIF ,Font.BOLD,17));
	            j.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createRaisedBevelBorder(), BorderFactory.createLoweredBevelBorder()));
	            Float temp = (Float)value;
	            temp = (float)(temp/0.7);
	            int i = temp.intValue();
	            String originalPrice = Integer.toString(i);
	            j.setText("Sale Price: "+Float.toString((Float)value)+"\nold price:\n       "+originalPrice); 
	            return j;
	        }
        }  
    }  
    
    class ButtonRenderer extends JButton implements TableCellRenderer 
    {
    	public ButtonRenderer() 
    	{setOpaque(true);}
    	public Component getTableCellRendererComponent(JTable table, Object value,boolean isSelected, boolean hasFocus, int row, int column)
    	{
    		if(column == 2)	
    			setText("Enlarge");
    		else 
    			if(column == 7)
    				setText("Add To Costum");
    		else
    			setText("Add / Remove");
    		return this;
    	}
    }
    
    class ButtonEditor extends DefaultCellEditor 
    {
    	private String label;
    	public ButtonEditor(JCheckBox checkBox) 
    	{
    		super(checkBox);
    	}
    	public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) 
    	{
    		if(column == 2)	
    		{
    			label = "Enlarge";
    			imgbutton.setText(label);
    			return imgbutton;
    		}
    		else 
    			if(column == 7)
    			{
        			label = "Add To Custom";
        			Custom.setText(label);
        			return Custom;
        		}
    		else
    			{
    				label = "Add / Remove";
    				cartbutton.setText(label);
    				return cartbutton;
    			}
    	}
    	public Object getCellEditorValue() 
    	{
    		return new String(label);
    	}
    }
}